<template>
  <div>
    <!-- 导航栏 -->
    <van-nav-bar title="登录" />
    <!-- 内容 -->
    <van-form @submit="doLogin">
      <van-field
        v-model="mobile"
        name="mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="rules.mobile"
      />
      <van-field
        v-model="code"
        name="code"
        label="验证码"
        placeholder="请输入验证码"
        :rules="rules.code"
      />
      <div style="margin: 16px">
        <van-button
          :loading="isLoading"
          loading-type="spinner"
          loading-text="加载中..."
          round
          block
          type="info"
          native-type="submit"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginAPI } from '@/api'
export default {
  data () {
    return {
      mobile: '13900898521',
      code: '246810',
      isLoading: false,
      // 效验规则
      rules: {
        mobile: [
          { required: true, message: '请填写手机号' },
          {
            pattern: /^1[2-9]\d{9}$/,
            message: '请填写正确的手机号',
            trigger: 'onBlur'
          }
        ],

        code: [
          { required: true, message: '请填写验证码' },
          { pattern: /^\d{6}$/, message: '请输入6位数字验证码' }
        ]
      }
    }
  },
  methods: {
    async doLogin (data) {
      // 开启加载状态
      this.isLoading = true
      try {
        const res = await loginAPI(data)
        // 登录成功
        // console.log(res)
        this.$toast.success('登录成功!')
        // 保存到vuex又保存到本地
        this.$store.commit('saveToken', res.data.data)
        // 判断是否带参数
        if (this.$route.query.back) {
          // 带了参数的直接跳回要去的页面
          this.$router.push(this.$route.query.back)
        } else {
          // 没带参数的直接去到首页
          this.$router.push('/layout/home')
        }
      } catch {
        //  登录失败
        // console.log('登录失败了')
        this.$toast.fail('登录失败!')
      }
      // 无论失败成功到进入到这来
      // 加载状态关闭
      this.isLoading = false
    }
  }
}
</script>

<style></style>
